/*
 * @Author: shiguang
 * @Date: 2023-04-27 11:26:33
 * @LastEditors: yusha
 * @LastEditTime: 2023-08-25 13:51:13
 * @Description: ContainerTabs
 */

import { Tabs } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { getSessionStorageByKey } from '@/utils';
import { ROUTER_BASENAME } from '@/config/router';
import { pushFullPath, setTabToLocal } from '../CKBLayout';

/**
 * 1. 展示所有的tabs
 * 2. 当前的 tab 要被选中
 * 3.
 */

export interface HistoryRouteItem {
  meta: {
    title?: string;
    auth?: string;
    keepAlive?: boolean;
  };
  fullPath: string;
  path: string;
  query?: Record<string, string>;
}

const ContainerTabs = () => {
    const location = useLocation();
    const currentPath = location.pathname;
    const currentFullPath = `${ROUTER_BASENAME}${currentPath}`;
    const navigate = useNavigate();
    const [activeKey, setActiveKey] = useState<string>(currentFullPath);
    const pushFullPathByNavigate = pushFullPath(navigate);

    const [historyRouters, setHistoryRouters] = useState<HistoryRouteItem[]>([]);
    useEffect(() => {
        const _currentFullPath = `${ROUTER_BASENAME}${location.pathname}`;
        setActiveKey(_currentFullPath);
        const [err, historyRouters] = getSessionStorageByKey<HistoryRouteItem[]>('routerLink', []);
        // console.log(1111111111, historyRouters);
        setHistoryRouters(historyRouters!);
    }, [location.pathname]);
    const onEdit = (targetKey: string | React.MouseEvent<Element, MouseEvent> | React.KeyboardEvent<Element>, action: 'add' | 'remove') => {
        if (action === 'remove' && typeof targetKey === 'string') {
            let preTabFullPath = '';
            let nextTabFullPath = '';
            const curHistoryRouters = historyRouters!.filter((item, idx) => {
                if (item.fullPath === targetKey) {
                    if (idx > 0) {
                        preTabFullPath = historyRouters![idx - 1].fullPath;
                    }
                    if (idx < historyRouters!.length - 1) {
                        nextTabFullPath = historyRouters![idx + 1].fullPath;
                    }
                    return false;
                }
                return true;
            }) ?? [];
            window.sessionStorage.setItem('routerLink', JSON.stringify(curHistoryRouters));
            // console.log(2222222, curHistoryRouters);
            setHistoryRouters(curHistoryRouters!);
            // 如果删除后 后面还有 tab 会匹配到后面的 tab
            if (nextTabFullPath) {
                return pushFullPathByNavigate(nextTabFullPath);
            }
            // 如果删除的是最后一个 tab 会匹配到前面的 tab
            if (preTabFullPath) {
                return pushFullPathByNavigate(preTabFullPath);
            }
        }
    };
    const items = historyRouters?.map((item, idx) => ({
        key: item.fullPath,
        label: item.meta.title,
        closable: idx > 0
    }));
    if (!items?.length) {
        return null;
    }
    // console.log('---------99999999999', items);
    return (
        <div className="x">
            <Tabs hideAdd onChange={pushFullPathByNavigate} activeKey={activeKey} type="editable-card" onEdit={onEdit} items={items} />
        </div>
    );
};
export default ContainerTabs;